package com.chevic.app;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import com.chevic.util.DBUtil;
import com.chevic.util.Util;

public class Weixin {

	static String TONKEN = "sinaapp520i";

	public String sign(HttpServletRequest request) throws Exception {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");

		String[] array = { timestamp, nonce,TONKEN };
		Arrays.sort(array);
		String result = array[0].toString() + array[1].toString() + array[2];

		String afterStr = Util.SHA1Encode(result) ;
		this.weixinLog(signature, timestamp, nonce, echostr, afterStr) ;
		if(afterStr.equalsIgnoreCase(signature)){
			return echostr;
		}else{
			return "error" ;
		}
	}
	
	public void weixinLog(String signature,String timestamp,String nonce,String echostr,String mycheckstr)throws Exception{
		String sql = "insert into wxlog (signature,timestamp,nonce,echostr,mycheckstr,logtime) values(?,?,?,?,?,?)" ;
		Connection conn = DBUtil.getConnR() ;
		PreparedStatement ps = conn.prepareStatement(sql) ;
		ps.setString(1, signature) ;
		ps.setString(2, timestamp) ;
		ps.setString(3, nonce) ;
		ps.setString(4, echostr) ;
		ps.setString(5, mycheckstr) ;
		ps.setString(6, Util.getCurrentTime()) ;
		ps.execute() ;
		ps.close() ;
		conn.close() ;
	}
	
}
